import React from 'react';
import FlatButton from 'material-ui/FlatButton';
import $ from 'jquery';
import Paper from 'material-ui/Paper';
import {RadioButton, RadioButtonGroup} from 'material-ui/RadioButton';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import ActionDone from 'material-ui/svg-icons/action/done';
import {myStyles} from '../utils';

export default class Answer extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            title: '',
            questions: [],//{desc,options:[{desc,id}],type}
            desc: '',//问卷描述
            selectedIds: [],//一个由选项index到选中值的map,每次重新链接需要清空
        }

        this.handleSubmit = this.handleSubmit.bind(this)
    }

    reAjax() {
        console.log(this.props.match.params.id)
        $.ajax({
            url: '/api/GetQuestionnaireById',
            data: {id: this.props.match.params.id},
            method: 'POST',
        }).then(res => {
            //console.log(JSON.stringify(res))
            if(!res.IsOk){
                alert('获取问卷失败')
                return
            }

            this.setState(this.formatState(res.Data))
        }, err => {
            alert('服务器响应错误')
        })
    }

    formatState(originData) {
        let data = originData
        if(typeof originData == 'string'){
            console.info('返回数据为字符串，尝试转化为对象')
            data = JSON.parse(originData)
        }

        const result = {
            desc: data["Describe"],
            title: data["Title"],
        }

        result.questions = data["QuestionCollection"].map(que => {

            const options = que["QuestionOptionCollection"].map(opt => {
                return {desc: opt["Describe"], id: opt["Id"]}
            })

            return {desc: que["Describe"], type: que["Type"], options}
        })

        console.info('Formatted: '+JSON.stringify(result))
        return result
    }

    reAjaxMock() {
        const mockData = {
            "Describe": "C++调查",
            "QuestionCollection": [
                {
                    "Describe": "C++难不难",
                    "QuestionOptionCollection": [
                        {
                            "Describe": "不难",
                            "Id": 1
                        },
                        {
                            "Describe": "难",
                            "Id": 2
                        }
                    ],
                    "Type": 0
                },
                {
                    "Describe": "Java难不难",
                    "QuestionOptionCollection": [
                        {
                            "Describe": "不难",
                            "Id": 3
                        },
                        {
                            "Describe": "难",
                            "Id": 4
                        }
                    ],
                    "Type": 0
                },
                {
                    "Describe": "计算机组成原理难不难",
                    "QuestionOptionCollection": [
                        {
                            "Describe": "难",
                            "Id": 5
                        },
                        {
                            "Describe": "很难",
                            "Id": 6
                        }
                    ],
                    "Type": 0
                }
            ],
            "Title": "课程满意度调查"
        }

        this.setState(this.formatState(mockData))
    }

    handleSelect(e,val,index){
        const selectedIds = [...this.state.selectedIds]
        selectedIds[index] = val
        this.setState({
            selectedIds
        })
        console.log(JSON.stringify(this.state.selectedIds))
    }

    componentDidMount() {
        this.componentReLinked()
    }

    //重新链接到这个页面
    componentReLinked(){
        this.reAjax()
        this.setState({
            selectedIds: []
        })
    }

    componentWillReceiveProps(nextProps) {
        this.componentReLinked()
    }

    handleSubmit(){
        $.ajax({
            url:'/api/PostQuestionFeedback',
            data: {IdCollection: this.state.selectedIds,SurveyId: this.props.match.params.id},
            method: 'POST',
        }).then(res =>{
            console.log('获取结果成功'+JSON.stringify(res))
            if(!res.IsOk){
                alert('答卷失败')
                return
            }
            alert('答卷成功')
        },err=>{
            alert('服务器相应错误')
        })
    }

    render() {
        console.log('Rendered')

        const ques = this.state.questions.map((que,index) => {
            const opts = que.options.map(opt =>
                (<RadioButton value={opt.id} label={opt.desc}/>)
            )

            return (
                <Paper style={myStyles.paper} zDepth={4}>
                    <h4>
                        {que.desc}
                    </h4>

                    <RadioButtonGroup name='questions' valueSelected={this.state.selectedIds[index]}  onChange={(e,val)=>{this.handleSelect(e,val,index)}}>
                        {opts}
                    </RadioButtonGroup>
                </Paper>
            )
        })

        return (
            <div style={myStyles.container}>
                <h2>{this.state.title || '标题载入中…'}</h2>

                <h4>{this.state.desc || '描述载入中…'}</h4>

                <div>
                    {ques.length > 1 ? ques : <h4>内容载入中…</h4>}
                </div>

                <FloatingActionButton onClick={this.handleSubmit}>
                    <ActionDone/>
                </FloatingActionButton>
            </div>
        )
    }
}